<template>
  <div class="page">
    <el-dialog class="gu_dia" title="" :visible.sync="dialogTableVisible" :close-on-click-modal="false"
               :close-on-press-escape="false" :show-close="false">
      <div v-if="init_page" class="initPage_div">
        <div style="margin:80px 0 0 350px">
          <img src="../../assets/img/lk-logos.png">
        </div>
        <div style="margin:100px 0 60px 102px;width:90%">
          <p class="titleSty">欢迎加入openLooKeng集群管理平台</p>
          <p class="titleSty">为更方便您使用该平台，请根据下面提示完善信息～</p>
        </div>
        <div class="gu_init">
          <p class="gu_init_p">①添加主机</p>
          <el-divider></el-divider>
          <p class="gu_init_p">②新建集群</p>
          <el-divider></el-divider>
          <p class="gu_init_p">③配置属性</p>
          <el-divider></el-divider>
          <p class="gu_init_p">④完成</p>
        </div>
        <span slot="footer" class="dialog-footer">
                <el-button type="primary" style="margin:60px 0 0 400px;width: 122px;height:40px;border-radius: 5px;"
                           @click="startCreate">开始创建</el-button>
            </span>
      </div>
      <div v-if="!init_page" v-loading="loadVis">
        <el-steps style="margin-left:110px;width:700px" :active="stepActive">
          <el-step title="添加主机"></el-step>
          <el-step title="新建集群"></el-step>
          <el-step title="配置属性"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <el-form style="margin-top:20px" v-if="addHostVisable" label-position="right" :rules="hostRules" label-width="100px" ref="addHostObj" :model="addHostObj">
          <el-form-item label="查找主机:">
            <div class="uploadForm">
              <span class="queryhost_title">您可以通过安装工具，提前规划配置，使用扩容工具进行快速扩容</span>
              <el-upload
               accept=".xls, .xlsx"
              :on-change="uploadChange"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
              :data="addHostObj"
              :headers="{authorization:token}"
              :on-error="uploadError"
              :action="uploadUrl"
              :on-remove="uploadRemove"
              :file-list="fileList">
                <el-button size="small" type="primary" v-loading="uploading">模板添加主机</el-button>
              </el-upload>
              <div style="margin:0 20px 0 20px">
                <a href="static/添加主机模板.xls" style="cursor: pointer;color:#409EFF">下载模板</a>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="主机名:" prop="name">
            <el-input maxlength="32" style="width:90%;" v-model.trim="addHostObj.name"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的名称，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="账ㅤ号:" prop="userName">
            <el-input maxlength="32" style="width:90%;" v-model.trim="addHostObj.userName"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加主机的账号，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="密ㅤ码:" prop="passWord">
            <el-input maxlength="32" type="password" style="width:90%;" v-model.trim="addHostObj.passWord"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的密码，字母大小写，字符，数字皆可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="端ㅤ口:" prop="port">
            <el-input maxlength="6" style="width:90%;" v-model.number="addHostObj.port"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的通讯端口(shell)，只需输入端口号即可</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="管理IP:" prop="ip">
            <el-input maxlength="32" style="width:90%;" v-model.trim="addHostObj.ip"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要添加的主机的管理IP地址，即当前登录的设备的IP，只需输入IP地址即可，无需输入端口号</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item label="业务IP:" prop="serviceIp">
            <el-input maxlength="32" style="width:90%;" v-model.trim="addHostObj.serviceIp"></el-input>
            <el-tooltip placement="right">
              <div slot="content" style="width:300px;">输入的是要当前登录账号的的通讯IP，只需输入IP地址即可，无需输入端口号</div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-form-item>
          <el-form-item class="query_sty">
            <el-button type="primary" @click="filterHandler(addHostObj)">查找</el-button>
          </el-form-item>
          <el-form-item style="margin-top:68px" v-if="queryHostListVis">
            <h3 class="quer_res">查找结果:</h3>
            <div style="display:flex;justify-content: flex-end;width:100%">
              <div class="quer_res2" style="width:100%">
                连接{{hostItemTableData.filter(item=>item.state
                =='ACTIVE').length}}台,未连接{{hostItemTableData.filter(item=>item.state !='ACTIVE').length}}台
              </div>
              <el-input placeholder="请输入管理IP" maxlength="16" clearable icon="el-icon-search" @input="queryHost"
                        v-model.trim="hostIp_query" style="width:163px;height:40px;margin:-30px 0 10px 0"></el-input>
            </div>
            <el-table :header-cell-style="{background:'#FAFAFA'}" :data="hostItemTableData" ref="multipleTable"
                      @selection-change="handleSelectionChange" style="width: 100%">
              <el-table-column :selectable="filterSelect" type="selection" width="55"></el-table-column>
              <el-table-column prop="name" disabled label="主机名称" width="180"></el-table-column>
              <el-table-column prop="ip" label="管理IP" width="180"></el-table-column>
              <el-table-column prop="serviceIp" label="业务IP" width="180"></el-table-column>
              <el-table-column prop="state" label="状态" width="100" :formatter="parseState">
                <template slot-scope="scope">
                  <div class="hostSty">
                    <i
                      :class="scope.row.state=='ACTIVE'?'iconfont icon-duigouzhong hostSty_i':'iconfont icon-chacha hostSty_i2' "></i>
                    <p>&nbsp;{{parseState(scope.row)}}</p>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item class="query_sty">
            <el-button @click="previousStep(0)">上一步</el-button>
            <el-button type="primary" @click="nextStep('addHostObj',2)">下一步</el-button>
          </el-form-item>
        </el-form>
        <el-form v-if="addClusterVisable" :model="addClusterObj" status-icon :rules="clusterRules" ref="addClusterObj" label-width="100px" class="addClusterForm">
          <el-row>
            <el-col :span="5">
              <el-form-item label="名ㅤㅤ称:" prop="name">
                <el-input maxlength="64" class="add_clu_input2" clearable v-model.trim="addClusterObj.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="主机列表:">
                <el-table border size="small" :header-cell-style="{background:'#FAFAFA'}" :data="multipleSelection">
                  <el-table-column align="center" prop="name" label="主机名称" width="125"></el-table-column>
                  <el-table-column align="center" prop="ip" label="管理IP" width="125"></el-table-column>
                  <el-table-column align="center" prop="serviceIp" label="业务IP" width="125"></el-table-column>
                  <el-table-column align="center" prop="nodeType" width="150" label="角色">
                    <el-table-column>
                      <template slot="header">
                        <div>
                          <el-checkbox v-model="selectAllWorkFlag" @change="selectAllWork"></el-checkbox>
                          worker({{workNodeNum}})
                        </div>
                      </template>
                      <template slot-scope="scope" class="node_div">
                        <el-checkbox style="margin-right:0;padding-left:40px" v-model="scope.row.workerNodes"
                                     @change="aloneSleWork"></el-checkbox>
                      </template>
                    </el-table-column>
                    <el-table-column>
                      <template slot="header">
                        <div>
                          <el-checkbox v-model="selectAllcoordinatorFlag" @change="selectAllcoordinator"></el-checkbox>
                          coordinator({{coordinatorNodeNum}})
                        </div>
                      </template>
                      <template slot-scope="scope" class="node_div">
                        <el-checkbox style="margin-right:0;padding-left:40px" v-model="scope.row.coordinator"
                                     @change="aloneSleCoordinator"></el-checkbox>
                      </template>
                    </el-table-column>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="安装地址:" prop="installationPath">
                <el-input placeholder="请输入安装地址" v-model="addClusterObj.installationPath"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="5">
              <el-form-item label="安装方式:" prop="upgradeWay">
                <el-select @change="clearaddClusterObjField" class="add_clu_input2" v-model="addClusterObj.upgradeWay" placeholder="请选择安装方式">
                  <el-option v-for="item in upgradeWays" :key="item.value" :label="item.label" :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row class="shangchuanRow">
            <el-col :span="18" style="display:flex">
              <el-form-item :label="addClusterObj.upgradeWay==2?'安 装 包 :':'版 本 号 :'" prop="fileId">
                <el-select  @focus="queryPackageList(addClusterObj.upgradeWay)" class="add_clu_input2" :loading="selectLoading" v-model="addClusterObj.fileId" :placeholder="addClusterObj.upgradeWay==2?'请选择安装包':'请选择版本号'">
                  <el-option v-for="item in packageFileList" :key="item.id" :label="item.version" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <i @click="showUploadPackage" class="iconfont icon-shangchuan shangchuanSty" v-if="addClusterObj.upgradeWay==2"></i>
            </el-col>
          </el-row>
          <el-row class="clus_next_sty">
            <el-col :span="4">
              <el-form-item>
                <el-button @click="previousStep(1)">上一步</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button type="primary" @click="nextStep('addClusterObj',3)">下一步</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <el-row v-if="basicConfigVis">
          <config @configSuccess="configSuccess" :checkVis="checkVis" :getHA="getHA" :guide="guide" :allIp="allIp" ref="config"></config>
          <div class="config_but_div">
            <el-button @click="previousStep(2)">上一步</el-button>
            <el-button type="primary" @click="nextStep(null,4)">下一步</el-button>
          </div>
        </el-row>

        <div v-if="completeVis" class="complete_div">
          <div v-if="imgVis" style="width:120px">
            <img :class="pauseVis?'imgCla_run':'imgCla_pause' " src="../../assets/img/形状.png">
            <div class="txt_div">
              配置中,请稍候<span :class="pauseVis?'loadTxt_run':'loadTxt_pause' "></span>
            </div>
          </div>
          <div v-else style="width:300px">
            <img src="../../assets/img/完成.png">
            <div>
              <p>配置成功！</p>
              <div class="txt_div2">
                即将为您跳转至首页ㅤ{{countdown}}<span :class="pauseVis?'loadTxt_run':'loadTxt_pause' "></span>
              </div>
              <el-button type="primary" @click="jumpNow">立即跳转</el-button>
            </div>
          </div>
        </div>
        <el-dialog @closed="diaBeforeClose" v-loading="uploadLoadVis" title="上传安装包" append-to-body
                   :visible.sync="uploadVis" width="720px" class="uploadDia">
          <el-upload style="text-align:center" accept=".tar.gz" class="upload-demo" drag :action="packageUploadUrl"
                     :on-success="uploadPackAgeSuccess" :before-upload="beforeUploadPackAge"
                     :on-exceed="uploadPackAgeExceed" :data="{version}" :headers="{authorization:token}"
                     :on-error="uploadPackAgeError"
                     :on-remove="uploadPackAgeRemove" :limit="10" :file-list="uploadPackageFileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <div style="text-align:center;margin-left:-60px;margin-top:10px">版本号:ㅤ
            <el-input style="width:360px;" v-model="version" placeholder="请输入版本号"></el-input>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="uploadVis = false">确 定</el-button>
          </div>
        </el-dialog>

        <el-dialog title="提示" :visible.sync="configHintVis" append-to-body width="540px">
          <div>
            <el-checkbox v-model="sureStart">安装后启动集群</el-checkbox>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="configHintVis = false">取 消</el-button>
            <el-button type="primary" @click="sureLateStart(4)">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-dialog>
  </div>
</template>
<script>
    import '../../assets/iconfont/iconfont.css'
    import {doGet, doPost} from '@/api/index.js'
    import '../../css/style.css'
    import config from '@/view/config/config'

    export default {
        components: {
            'config': config,
        },
        data() {
            var checnClusterName = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('名称不能为空'))
                }
                if (!value.match('^[a-zA-Z0-9]+$')) {
                    callback(new Error('请输入数字或字母'))
                } else {
                    callback()
                }
            }
            return {
              allIp:[],
              guide:true,
              getHA:false,
                checkVis: false,
                queryHostListVis: false,
                workNodeNum: 0,
                coordinatorNodeNum: 0,
                selectAllWorkFlag: false,
                selectAllcoordinatorFlag: false,
                proKeyName: '',
                sureStart: false,
                countdown: 3,
                selectLoading: false,
                uploadLoadVis: false,
                loadVis: false,
                multipleSelection: [],
                token: '',
                hostItemTableData: [],
                hostItemTableData_copy: [],
                uploadUrl: `${process.env.UPLOAD_PARAM}/sys_ecs/analysisExcel`,
                packageUploadUrl: `${process.env.UPLOAD_PARAM}/sys_file/uploadFile`,
                fileList: [],
                packageFileList: [],
                uploadPackageFileList: [],
                hostList: [],
                uploadVis: false,
                innerVisible: true,
                imgVis: true,
                completeVis: false,
                tabItemName: '1',
                tabName: 'first',
                basicConfigVis: false,
                addHostVisable: true,
                addClusterVisable: false,
                configAttrVisable: false,
                init_page: true,
                stepActive: 0,
                addHostObj: {
                    name: '',
                    userName: '',
                    passWord: '',
                    port: 22,
                    serviceIp: '',
                    ip: ''
                },
                addClusterObj: {
                    name: '',
                    upgradeWay: '1',
                    type: 1,
                    version: '',
                    fileId: '',
                    installationPath:'/opt/openlookeng/',
                },
                dialogTableVisible: true,
                hostRules: {
                    name: [{required: true, message: '请输入名称', trigger: 'blur'}],
                    userName: [{required: true, message: '请输入账号', trigger: 'blur'}],
                    passWord: [{required: true, message: '请输入密码', trigger: 'blur'}],
                    port: [{required: true, type: 'number', message: '请输入端口号(数字)', trigger: 'blur'}],
                    serviceIp: [{required: true, message: '请输入业务ip', trigger: 'blur'}],
                    ip: [{required: true, message: '请输入管理ip', trigger: 'blur'}],
                },
                clusterRules: {
                    name: [{validator: checnClusterName, trigger: 'change'}],
                    installationPath: [{required: true, message: '请输入安装地址', trigger: 'change'}],
                    upgradeWay: [{required: true, message: '请选择安装方式', trigger: 'blur'}],
                    fileId: [{required: true, message: '请选择', trigger: 'blur'}],
                },
                upgradeWays: [{label: '在线', value: '1'}, {label: '离线', value: '2'}],
                addNodes: [],
                data: {
                    'log': {
                        'log1': {
                            'io.prestosql': 'DEBUG'
                        }
                    },
                    'common': {
                        'common1': {
                            'node.launcher-log-file': '/opt/openlookeng/hetu-server-1.1.0/log/launch.log',
                            'node.server-log-file': '/opt/openlookeng/hetu-server-1.1.0/log/server.log',
                            'catalog.config-dir': '/opt/openlookeng/hetu-server-1.1.0/etc/catalog',
                            'node.data-dir': '/opt/openlookeng/hetu-server-1.1.0/data',
                            'plugin.dir': '/opt/openlookeng/hetu-server-1.1.0/plugin',
                            'node.environment': '',
                        }
                    },
                    'jvm': {
                        'jvm1': {
                            'jvm': '-server \n-Xmx16G \n-XX:-UseBiasedLocking \n-XX:+UseG1GC \n-XX:G1HeapRegionSize=32M \n-XX:+ExplicitGCInvokesConcurrent \n-XX:+ExitOnOutOfMemoryError \n-XX:+UseGCOverheadLimit \n-XX:+HeapDumpOnOutOfMemoryError \n-XX:ReservedCodeCacheSize=512M \n-Djdk.attach.allowAttachSelf=true \n-Djdk.nio.maxCachedBufferSize=2000000'
                        }
                    },
                },
                runStates: [{
                    value: 'ACTIVE',
                    label: '运行中'
                }, {
                    value: 'INACTIVE',
                    label: '未连接'
                }, {
                    value: 'SHUTTING_DOWN',
                    label: '关闭'
                }],
                version: '',
                hostIp_query: '',
                configHintVis: false,
                pauseVis: true,
                timer: '',
                uploading:false
            }
        },
        mounted() {
            this.token = JSON.parse(localStorage.getItem('userInfo')).authorization
        },
        watch: {
            selectAllWorkFlag() {
                this.workNodeNum = this.multipleSelection.filter(item => item.workerNodes).length
            },
            selectAllcoordinatorFlag() {
                this.coordinatorNodeNum = this.multipleSelection.filter(item => item.coordinator).length
            },
            countdown() {
                if (this.countdown < 1) {
                    this.jumpNow()
                    clearInterval(this.timer)
                }
            }
        },
        methods: {
            aloneSleWork(val) {
                this.workNodeNum = this.multipleSelection.filter(item => item.workerNodes).length
                this.selectAllWorkFlag = false
                if (this.workNodeNum == this.multipleSelection.length) {
                    this.selectAllWorkFlag = true
                }
            },
            aloneSleCoordinator(val) {
                this.coordinatorNodeNum = this.multipleSelection.filter(item => item.coordinator).length
                this.selectAllcoordinatorFlag = false
                if (this.coordinatorNodeNum == this.multipleSelection.length) {
                    this.selectAllcoordinatorFlag = true
                }
            },
            selectAllWork(val) {
                this.multipleSelection.forEach(item => {
                    item.workerNodes = val
                })
            },
            selectAllcoordinator(val) {
                this.multipleSelection.forEach(item => {
                    item.coordinator = val
                })
            },
            sureLateStart(index) {
                this.saveNextStep(index)
            },
            queryHost() {
                this.hostItemTableData = this.hostItemTableData_copy.slice(0)
                if (this.hostIp_query) {
                    this.hostItemTableData = this.hostItemTableData.filter(item => item.ip.indexOf(this.hostIp_query) != -1)
                }
            },
            filterHandler(obj) {
                let url = '/sys_ecs/checkHost'
                let list = this.hostItemTableData_copy.slice(0)
                if (obj.name && obj.userName && obj.passWord && obj.port && obj.ip && obj.serviceIp) {
                    let filterList = list.filter(item => item.ip == obj.ip);
                    let newObj = JSON.parse(JSON.stringify(obj));
                    if (filterList.length == 0) {
                        list.push(newObj);
                    } else {
                        filterList[0].name = newObj.name;
                        filterList[0].userName = newObj.userName;
                        filterList[0].passWord = newObj.passWord;
                        filterList[0].port = newObj.port;
                        filterList[0].serviceIp = newObj.serviceIp;
                    }
                } else {
                    if (list.length == 0) {
                        return this.$message.error("请上传文件或输入主机信息!");
                    }
                }
                this.loadVis = true
                doPost(url, list).then(res => {
                    if (res.data.code == 0) {
                        this.hostItemTableData = res.data.data
                        this.hostItemTableData_copy = this.hostItemTableData.slice(0)
                        this.$message({type: 'success', message: res.data.msg})
                        this.queryHostListVis = true
                    }
                    this.loadVis = false
                })
            },
            clearaddClusterObjField() {
                this.addClusterObj.fileId = ''
            },
            diaBeforeClose() {
                this.version = ''
            },
            configCluster() {
                let fileId = this.addClusterObj.fileId
                let url = `/sys_openlookeng_cluster/deployCluster?fileId=${fileId}&isStart=${this.sureStart}`
                let self = this
                //after configure success
                doPost(url).then(res => {
                    if (res.data.code == 0) {
                        self.imgVis = false
                        self.timer = setInterval(() => {
                            self.countdown = self.countdown - 1
                        }, 1000)
                    } else {
                        this.pauseVis = false
                    }
                })
            },
            jumpNow() {
                this.$router.push('/bashbord')
            },
            queryPackageList(way) {
                if (way) {
                    this.selectLoading = true
                    let url = '/sys_file/listFileNoPage?upgradeWay=' + way
                    doGet(url).then(res => {
                        this.selectLoading = false
                        if (res.data.code == 0) {
                            this.packageFileList = res.data.data
                        }
                    })
                }
            },
            showUploadPackage() {
                this.uploadPackageFileList = []
                this.uploadVis = true
            },
            beforeUploadPackAge(file) {
                const fileTypeLim = file.name.indexOf('tar.gz') != -1
                if (!fileTypeLim) {
                  this.$message.error('只能上传 tar.gz 格式文件!')
                  return false
                }
                if (this.version.trim()=='') {
                  this.$message.error('请输入本次上传的安装包的版本号!')
                  return false
                }
                this.uploadLoadVis = true
                return true
            },
            uploadPackAgeSuccess(response, file, fileList) {
                this.uploadLoadVis = false
                if (response.code == 0) {
                } else {
                    for (let i in fileList) {
                        if (fileList[i].uid == file.uid) {
                            this.uploadPackageFileList.splice(i, 1)
                        }
                    }
                    return this.$message.error(response.msg)
                }
            },
            uploadPackAgeExceed() {
                this.$message.error('最大上传数为10')
                return false
            },
            uploadPackAgeError(err, file, fileList) {
                this.uploadLoadVis = false
            },
            uploadPackAgeRemove(file, fileList) {
                for (let i in fileList) {
                    if (fileList[i].uid == file.uid) {
                        this.uploadPackageFileList.splice(i, 1)
                    }
                }
            },
            listHostIdByIp(msg, index) {
                let ips = []
                this.multipleSelection.forEach(item => ips.push(item.ip))
                let url = '/sys_ecs/getEcss'
                doPost(url, ips).then(res => {
                    if (res.data.code == 0) {
                        this.multipleSelection.forEach(item => {
                            for (let o in res.data.data) {
                                if (item.ip == res.data.data[o].ip) {
                                    item.id = res.data.data[o].id
                                    break
                                }
                            }
                        })
                        this.$message({type: 'success', message: msg})
                        this.pageVisable(index)
                    }
                })
            },
            filterSelect(row, index) {
                if (row.state == 'ACTIVE') {
                    return true
                }
                return false
            },
            uploadChange(file, fileList) {
                if (fileList.length > 1) {
                    fileList.splice(0, 1)
                }
            },
            uploadSuccess(response, file, fileList)
            {
              this.loadVis = false
              if (response.code == 0)
              {
                this.uploading=false;
                this.hostItemTableData = []
                this.hostItemTableData = response.data
                this.hostItemTableData_copy = this.hostItemTableData.slice(0)
                this.$message({type: 'success', message: response.msg})
              }
              else
              {
                this.uploading=false;
                this.$message.error("上传的文件内容有误，请检查")
              }
              this.fileList = [];
            },
            beforeUpload(file) {
              this.uploading=true;
              let split = file.name.split(".");
              var fileName = split[split.length - 1];
              const fileTypeLim = fileName === 'xls' || fileName === 'xlsx'
              const fileSizeLim = file.size / 1024 / 1024 < 5
              if (!fileTypeLim) {
                this.$message.error('只能上传 xls或xlsx 格式文件!')
                this.uploading=false;
                return
              }
              if (!fileSizeLim) {
                this.$message.error('上传文件大小不能超过 5MB!')
                this.uploading=false;
                return
              }
              this.loadVis = true
              return fileTypeLim && fileSizeLim
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            uploadError(err, file, fileList) {
              this.fileList = []
              this.loadVis = false
              this.uploading=false;
            },
            uploadRemove() {
              this.fileList = []
            },
            startCreate() {
                this.checkInitGuide().then(res => {
                    if (res.data.code == 0) {
                        this.stepActive = 1
                        this.init_page = false
                    } else {
                        this.$router.push('/bashbord');
                    }
                })
            },
            checkInitGuide() {
                return new Promise((resolve, reject) => {
                    let apiUrl = '/sys_openlookeng_cluster/v2/checkGuide'
                    let param = {}
                    doGet(apiUrl, param).then((response) => {
                        resolve(response)
                    }).catch(err => {
                        reject(err)
                    })
                })
            },
            previousStep(index) {
                this.allIp = [];
                this.pageVisable(index)
            },
            saveConfig(index) {
                this.configHintVis = false
                this.pageVisable(index)
                this.configCluster()
            },
            saveNextStep(index) {
                if (index == '2') {
                    this.saveHost(this.multipleSelection, index)
                } else if (index == '3') {
                    this.multipleSelection.forEach(item => {
                        if (item.workerNodes && item.coordinator) {
                            item.nodeType = 'ALL'
                        } else if (item.coordinator) {
                            item.nodeType = 'COORDINATOR'
                        } else if (item.workerNodes) {
                            item.nodeType = 'WORKER_NODES'
                        }
                    })
                    let o = this.multipleSelection.filter(item => item.nodeType == undefined)
                    if (o.length != 0) {
                        this.allIp=[];
                        return this.$message.error('角色不能为空!')
                    }
                    let hostObjs = []
                    this.multipleSelection.forEach(item => {
                        let obj = {
                            ecsId: item.id,
                            nodeType: item.nodeType
                        }
                        hostObjs.push(obj)
                    })
                    this.addClusterObj.dtos = hostObjs
                    this.saveCluster(this.addClusterObj, index)
                } else if (index == '4') {
                    this.saveConfig(index)
                } else {
                    this.pageVisable(index)
                    this.stepActive = index
                }
            },
            hostSubmit(name, obj) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        let filterList = this.hostItemTableData.filter(item => obj.ip == item.ip)
                        if (filterList.length > 0) {
                            return this.$message.error('该主机已存在于待选择区域,请勿重复添加!')
                        }
                        this.loadVis = true
                        let url = '/sys_ecs/checkHost'
                        let list = []
                        list.push(JSON.parse(JSON.stringify(obj)))
                        doPost(url, list).then(res => {
                            if (res.data.code == 0) {
                                this.hostItemTableData.push(JSON.parse(JSON.stringify(obj)))
                                this.hostItemTableData_copy = this.hostItemTableData.slice(0)
                                this.$message({type: 'success', message: res.data.msg})
                            }
                            this.loadVis = false
                        })
                    }
                })
            },
            nextStep(name, index)
            {
                let count=0;
                if (index == 0)
                {
                  this.addHostVisable = true
                  this.addClusterVisable = false
                }
                else
                {
                  if (index == '2' && this.multipleSelection.length == 0)
                  {
                    return this.$message.error('请选择需要添加的主机!')
                  }
                  else if (index == '2' && this.multipleSelection.length != 0)
                  {
                    this.saveNextStep(index)
                  }
                  else if (index == '4')
                  {
                    this.$refs.config.modifyConfigList()
                  }
                  else
                  {
                    for(let i=0;i<this.multipleSelection.length;i++)
                    {
                      if(this.multipleSelection[i].coordinator)
                      {
                        this.allIp.push(this.multipleSelection[i].serviceIp+':5701');
                        count++;
                      }
                    }
                    this.allIp = JSON.stringify(this.allIp)
                    for(let j=0;j<this.multipleSelection.length;j++)
                    {
                      if(this.multipleSelection[j].coordinator)
                      {
                        localStorage.setItem("serviceIp",JSON.stringify(this.multipleSelection[j].serviceIp))
                      }
                    }
                    if(count>=2)
                    {
                      this.getHA = true;
                    }
                    else
                    {
                      this.getHA = false;
                    }
                    this.$refs[name].validate((valid) =>
                    {
                      if (valid && count!=0)
                      {
                        this.saveNextStep(index)
                      }
                      else
                      {
                        this.allIp = [];
                        if(count==0){
                          this.$message.error('至少勾选一个协调节点!')
                        }
                        return false
                      }
                    })
                  }
              }
            },
            configSuccess() {
                this.configHintVis = true
            },
            saveCluster(obj, index) {
                this.loadVis = true
                let url = '/sys_openlookeng_cluster/insertCluster'
                doPost(url, obj).then(res => {
                    this.loadVis = false;
                    if (res.data.code == 0) {
                        // this.$refs.config.initData();
                        this.pageVisable(index)
                        this.stepActive = index
                        this.$message({type: 'success', message: res.data.msg})
                        this.data.common.common1['node.environment'] = obj.name
                        this.checkVis = true
                    }else{
                      this.allIp = [];
                    }
                })
            },
            saveHost(obj, index) {
                this.loadVis = true
                let url = '/sys_ecs/add'
                doPost(url, obj).then(res => {
                    this.loadVis = false
                    if (res.data.code == 0) {
                        if (Object.keys(res.data.data).length != 0) {
                            let msg = ''
                            Object.keys(res.data.data).forEach((key) => {
                                msg += key + JSON.stringify(res.data.data[key]) + '<br>'
                            })
                            if (msg) {
                                this.$alert(msg, '提示', {
                                    dangerouslyUseHTMLString: true
                                })
                            }
                        } else {
                            this.listHostIdByIp(res.data.msg, index)
                        }
                    }
                })
            },
            parseState(row, column) {
                return this.runStates.filter(item => item.value == row.state)[0].label
            },
            pageVisable(index) {
                if (index == 0) {
                    this.init_page = true
                } else {
                    if (index == 1) {
                        this.addHostVisable = true
                        this.addClusterVisable = false
                        this.basicConfigVis = false
                        this.completeVis = false
                        this.$nextTick(() => {
                          this.multipleSelection.forEach(item=>{
                            this.$refs.multipleTable.toggleRowSelection(item,true);
                          });
                        });
                    } else if (index == 2) {
                        this.addHostVisable = false
                        this.addClusterVisable = true
                        this.basicConfigVis = false
                        this.completeVis = false
                    } else if (index == 3) {
                        this.addHostVisable = false
                        this.addClusterVisable = false
                        this.basicConfigVis = true
                        this.completeVis = false
                    } else if (index == 4) {
                        this.addHostVisable = false
                        this.addClusterVisable = false
                        this.basicConfigVis = false
                        this.completeVis = true
                    }
                    this.stepActive = index
                }
            }
        },
    }
</script>
<style scoped>
  .clus_next_sty {
    display: flex;
    justify-content: center;
  }


  .addClusterForm {
    margin-top: 30px;
    width: 900px;
  }

  .addClusterForm .el-row {
    width: 80%;
  }

  .query_sty {
    display: flex;
    justify-content: center;
  }

  .queryhost_title {
    width: 348px;
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 40px;
    margin-right: 81px;
  }

  .quer_res2 {
    width: 137px;
    height: 17px;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #999999;
    line-height: 17px;
  }

  .quer_res {
    width: 80px;
    height: 22px;
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 22px;
    margin-top: -20px;
  }

  .hostSty {
    display: flex;
    margin: -10px 0px;
  }

  .hostSty_i {
    line-height: 52px;
    font-size: 20px;
    color: #5EDD86;
  }

  .hostSty_i2 {
    line-height: 52px;
    font-size: 20px;
    color: #D81E06;
  }

  .txt_div {
    display: flex;
    margin-left: 10px;
  }

  .txt_div2 {
    display: flex;
    padding-left: 80px;
  }

  .loadTxt_run:after {
    overflow: hidden;
    display: inline-block;
    vertical-align: bottom;
    animation: ellipsis 2s infinite;
    animation-play-state: running;
    -webkit-animation-play-state: running;
    content: "\2026";
  }

  .loadTxt_pause:after {
    overflow: hidden;
    display: inline-block;
    vertical-align: bottom;
    animation: ellipsis 2s infinite;
    animation-play-state: paused;
    -webkit-animation-play-state: paused;
    content: "\2026";
  }

  @keyframes ellipsis {
    from {
      width: 2px;
    }
    to {
      width: 15px;
    }
  }

  @-webkit-keyframes ellipsis {
    from {
      width: 2px;
    }
    to {
      width: 15px;
    }
  }

  @keyframes configLoading {
    0% {
      transform: rotate(0deg)
    }
    100% {
      transform: rotate(360deg)
    }
  }

  @-webkit-keyframes configLoading {
    0% {
      transform: rotate(0deg)
    }
    100% {
      transform: rotate(360deg)
    }
  }

  .imgCla_pause {
    animation: configLoading 3s linear infinite;
    animation-play-state: paused;
    -webkit-animation-play-state: paused
  }

  .imgCla_run {
    animation: configLoading 3s linear infinite;
    animation-play-state: running;
    -webkit-animation-play-state: running
  }

  .titleSty {
    height: 28px;
    font-size: 20px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 28px
  }

  .uploadDia {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .complete_div {
    width: 100%;
    height: 200px;
    display: flex;
    justify-content: center;
    margin-top: 50px;
    text-align: center;
  }

  .page {
    background-color: rgba(255, 255, 255, 1);
  }

  .gu_dia {
    width: 1920px;
    height: 100%;
  }

  .gu_init {
    display: flex;
    width: 600px;
    padding-left: 188px;
  }

  .initPage_div {
    width: 100%;
  }

  .gu_init_p {
    width: 800px;
    height: 25px;
    font-size: 18px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    line-height: 10px
  }

  .config_but_div {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }

  .toolsty .el-form-item {
    display: flex;
    flex-direction: row;
  }

  .inputWidth {
    margin-left: -160px;
    width: 500px;
  }

  .inputWidths {
    width: 400px;
  }

  .uploadForm {
    display: flex;
  }

  .node_div {
    display: flex;
    justify-content: center;
  }

  .shangchuanSty {
    color: #409EFF;
    font-size: 28px !important;
    line-height: 40px;
    cursor: pointer;
    padding-left: 10px;
  }

  .shangchuanRow {
    display: flex;
  }

</style>
